
from django.http import HttpResponse
from django.views.generic import View
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView

from .models import News
from .serializers import NewsGetSerializer, NewsSerializer

"""
 DRF实现CBV
 取消注释csrf
"""
class NewsView(APIView):
    def get(self, request, *args, **kwargs):
        if 'pk' in kwargs:
            new = News.objects.get(pk=kwargs['pk'])
            serializer = NewsGetSerializer(instance=new)
            return Response(serializer.data, status=200)
        queryset = News.objects.select_related('category')
        serializer = NewsGetSerializer(instance=queryset, many=True)
        return Response(serializer.data, status=200)
    def post(self, request: Request):
        serializer = NewsSerializer(data=request.data)
        # 有异常抛出
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=200)
        return Response(serializer.errors, status=404)
    def put(self, request: Request,pk):
        instance = News.objects.get(pk=pk)
        serializer = NewsSerializer(instance=instance, data=request.data)
        # 有异常抛出
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=200)
        return Response(serializer.errors, status=404)
    def delete(self, request: Request, pk):
        queryset = News.objects.filter(pk=pk)
        if queryset.exists():
            queryset.first().delete()
            return Response({'code': 200, 'msg': '删除成功'}, status=200)
        return Response({'code': 200, 'msg': '删除失败'}, status=404)